<?php

class MOrder extends Model {

    function __construct() {
        parent::__construct();
        $this->table = "cms_order";
    }

    //搜索产品列表
    public function selectLists($search,$page,$page_size=20) {
        $sql_data = array('is_delete' => '0');
        $search_field = array('cus_id','cus_mobile','cus_name','cus_address');
        $result = $this->selectAll($this->table,$sql_data,$page,$page_size,$search,$search_field);
        return $result;
    }
    
    //搜索产品总数
    public function selectCounts($search) {
        $sql_data = array('is_delete' => '0');
        $search_field = array('cus_id','cus_mobile','cus_name','cus_address');
        $result = $this->selectCount($this->table,$sql_data, $search,$search_field);
        return $result;
    }

    //新增订单
    public function insert($data, $p_count) {
        $result = $this->insertRow($this->table, $data);
        //生成订单,减库存
        if ($result) {
            $product = new MProduct();
            $up_count_results = $product->updateCounts($p_count);
        }
        //生成订单,减用户余额(余额大于0,扣余额)
        if ($result) {
            $customer = new MCustomer();
            $cus_info = $customer->selectInfo($data['cus_id']);
            if ($cus_info['balance'] > 0) {
                $customer->updateDiscount($data['cus_id'], $data['price'] + $data['exp_charge']);
            }
        }
        return $result;
    }

    //删除订单
    public function del($id) {
        $data = array('is_delete' => 1);
        $where = " where id= $id";
        $result = $this->updateRow($this->table, $data, $where);

        if ($result) {
            $order = $this->selectInfo($id);
            if ($order) {
                //删除订单,恢复库存
                $new_product = array();
                $products = $order['order_desc'];
                $products = json_decode($products, TRUE);
                foreach ($products as $key => $val) {
                    $new_product[$val['id']] = $val['count'];
                }
                $product = new MProduct();
                $product->updateCounts($new_product, '+');

                //删除订单,恢复用户余额(有余额,恢复)
                $customer = new MCustomer();
                $cus_info = $customer->selectInfo($order['cus_id']);
                if ($cus_info['balance'] > 0) {
                    $customer->updateDiscount($order['cus_id'], $order['price'] + $order['exp_charge'], '+');
                }
            }
        }
        return $result;
    }

    //查询订单信息
    public function selectInfo($id) {
        $sql_data = array('id' => $id);
        $result = $this->selectRow($this->table, $sql_data);
        return $result;
    }

}
